/*
 * @Description: 系统消息管理
 * @Author: DHL
 * @Date: 2022-11-27 15:51:45
 * @LastEditors: dhlleo dhlleo@126.com
 * @LastEditTime: 2022-12-03 10:58:09
 */

import { log } from '/@/utils/log'
import { ElMessage } from 'element-plus'
import { cloneDeep, assign } from 'lodash-es'
import { MessageModel } from '/@/api/system/model/messageModel'
import { apiMessageGetById, apiMessageSave, apiMessageUpdateById } from '/@/api/system/message'
import organizationTree from '/@/pages/components/organizationTree.vue'
import selectUser from '/@/pages/components/selectUser.vue'
import { arrayRemoveByPropertyValue, arraySerialize } from '/@/utils/twUtils'
import { useCacheData } from '/@/hooks/web/cacheData'
import { ProjectListResultModel, ProjectModel } from '/@/api/system/model/projectModel'
import { apiProjectList } from '/@/api/system/project'
import { UserModel } from '/@/api/system/model/userModel'
import { OrganizationModel } from '/@/api/system/model/organizationModel'

export default defineComponent({
  name: 'MessageForm',
  components: { organizationTree, selectUser },
  emits: ['refreshTableData'],
  setup(props, { emit, expose }) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////
    const dbFormRef = ref()
    const loading = ref(true)

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 显示弹框
     */
    const visible = ref(false)

    /**
     * 标题
     */
    const title = computed(() => {
      let rtn = ''
      switch (action.value) {
        case 'add':
          rtn = '新增'
          break
        case 'edit':
          rtn = '编辑'
          break
        default:
          rtn = '查看'
          break
      }
      return rtn
    })

    /**
     * 公共
     */
    const state = reactive({
      messageType: useCacheData().getDic('MESSAGE_TYPE'),
      messagePriority: useCacheData().getDic('MESSAGE_PRIORITY'),
      messageReceivorType: useCacheData().getDic('MESSAGE_RECEIVOR_TYPE'),
      receivorOrgList: [] as Array<OrganizationModel>,
      receivorUserList: [] as Array<UserModel>,
      projectList: [] as Array<ProjectModel>
    })

    //////////////////////////////////////////////////
    // 表单
    //////////////////////////////////////////////////

    const defaultForm = {
      id: '', // 编号
      projectId: '', // 项目ID
      title: '', // 标题
      content: '', // 内容
      priority: '1', // 优先级
      receivorType: '1', // 接收方类型
      receivorOrgIds: '', // 接收方为公司/部门的id
      type: '1', // 消息类型（1：公告；2：通知；3-审批）
      senderId: '', // 发送人ID
      sender: '', // 发送人
      status: '0', // 状态（0：待发布；1：已发布；2：已撤销）
      revokerId: '', // 撤销者ID
      revoker: '', // 撤销人
      revokeReason: '', // 撤销原因
      bizUrl: '', // 业务页面地址
      receivorIds: []
    }

    let dbForm = reactive<MessageModel>(cloneDeep(defaultForm))

    //////////////////////////////////////////////////
    // 表单验证规则
    //////////////////////////////////////////////////

    /**
     * 表单验证规则
     */
    const rules = reactive({
      projectId: [
        {
          required: true,
          message: '请选择项目',
          trigger: 'blur'
        }
      ],
      title: [
        {
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        },
        {
          max: 200,
          message: '最多可输入200个字符',
          trigger: 'blur'
        }
      ],
      content: [
        {
          required: true,
          message: '请输入内容',
          trigger: 'blur'
        },
        {
          max: 4294967295,
          message: '最多可输入4294967295个字符',
          trigger: 'blur'
        }
      ],
      priority: [
        {
          required: true,
          message: '请选择优先级',
          trigger: 'blur'
        },
        {
          max: 10,
          message: '最多可输入10个字符',
          trigger: 'blur'
        }
      ],
      receivorType: [
        {
          required: true,
          message: '请选择接收方类型 ',
          trigger: 'blur'
        },
        {
          max: 10,
          message: '最多可输入10个字符',
          trigger: 'blur'
        }
      ],
      receivorIds: [
        {
          required: true,
          message: `请选择`,
          trigger: 'blur'
        }
      ],
      type: [
        {
          required: true,
          message: '请选择消息类型',
          trigger: 'blur'
        },
        {
          max: 10,
          message: '最多可输入10个字符',
          trigger: 'blur'
        }
      ]
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 提交表单
     */
    function handleSubmit(isContinue: boolean) {
      if (isContinue) {
        dbForm.status = '1' // 保存并发布
      } else {
        dbForm.status = '0' // 暂存待发布
      }

      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun(isContinue)
          } else {
            editFun()
          }
        } else {
          log.warn('系统消息管理', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun(isContinue: boolean) {
      loading.value = true
      apiMessageSave(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset()
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiMessageUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            handleReset()
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 重置表单
     * @param isClosed 是否关闭弹框
     */
    function handleReset() {
      assign(dbForm, cloneDeep(defaultForm))
      emit('refreshTableData')
      visible.value = false
    }

    /**
     * 接收方类型改变事件
     */
    function handleChangeReceivorType() {
      state.receivorOrgList = []
      state.receivorUserList = []
      dbForm.receivorIds = []
    }

    //////////////////////////////////////////////////
    // 选择机构
    //////////////////////////////////////////////////
    const orgTreeRef = ref()

    /**
     * 选中事件
     */
    function handleNodeClick() {
      const orgs = orgTreeRef.value.getChecked()
      state.receivorOrgList = orgs.orgList
      dbForm.receivorIds = arraySerialize(state.receivorOrgList, 'id')
    }

    /**
     * 机构删除
     * @param org
     */
    function handleOrgDelete(org) {
      arrayRemoveByPropertyValue(state.receivorOrgList, 'id', org.id)
      dbForm.receivorIds = arraySerialize(state.receivorOrgList, 'id')
    }

    /**
     * 机构树组件显示
     */
    function handleOrgTreeShow() {
      nextTick(() => {
        orgTreeRef.value.setChecked(dbForm.receivorIds)
      })
    }

    //////////////////////////////////////////////////
    // 选择用户
    //////////////////////////////////////////////////
    /**
     * 用户选择
     */
    const selectUserRef = ref()

    /**
     * 弹出选择用户
     */
    function handleSelectUserOpen() {
      selectUserRef.value.handleOpen(state.receivorUserList)
    }

    /**
     * 选择用户确认
     * @param userList
     */
    function handleSubmitSelectUser(userList) {
      state.receivorUserList = userList
      dbForm.receivorIds = arraySerialize(userList, 'id')
    }

    /**
     * 删除用户
     */
    function handleUserDelete(user) {
      arrayRemoveByPropertyValue(state.receivorUserList, 'id', user.id)
      dbForm.receivorIds = arraySerialize(state.receivorUserList, 'id')
    }

    //////////////////////////////////////////////////
    // 查询项目
    //////////////////////////////////////////////////
    /**
     * 查询项目列表
     */
    function handleSearchProjectList() {
      apiProjectList({}).then((result: ProjectListResultModel) => {
        if (result?.success && result.data) {
          state.projectList = result.data
        }
      })
    }

    //////////////////////////////////////////////////
    // 打开 、 关闭
    //////////////////////////////////////////////////
    /**
     * 打开弹框
     */
    function handleOpen(actionParam: string, rowParam?: MessageModel) {
      visible.value = true
      loading.value = false
      action.value = actionParam

      handleSearchProjectList()

      nextTick(() => {
        state.receivorOrgList = []
        state.receivorUserList = []
        dbForm.receivorIds = []

        if (['edit', 'view'].indexOf(actionParam) > -1 && rowParam) {
          apiMessageGetById(rowParam.id || '').then((result) => {
            if (result?.success) {
              assign(dbForm, cloneDeep(result.data))
              if (['2', '3'].includes(dbForm.receivorType || '')) {
                state.receivorOrgList = result.data.orgs || []
                dbForm.receivorIds = arraySerialize(result.data.orgs || [], 'id')
              } else if (dbForm.receivorType === '4') {
                state.receivorUserList = result.data.users || []
                dbForm.receivorIds = arraySerialize(result.data.users || [], 'id')
              }
            } else {
              ElMessage.error(result?.message)
            }
          })
        }
      })
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      assign(dbForm, cloneDeep(defaultForm))
      visible.value = false
    }

    /**
     * 暴露函数
     */
    expose({ handleOpen })

    return {
      loading,
      visible,
      action,
      title,
      state,
      dbFormRef,
      dbForm,
      rules,
      handleOpen,
      handleClose,
      handleSubmit,
      handleReset,
      orgTreeRef,
      handleNodeClick,
      handleOrgDelete,
      selectUserRef,
      handleSelectUserOpen,
      handleSubmitSelectUser,
      handleUserDelete,
      handleChangeReceivorType,
      handleOrgTreeShow
    }
  }
})
